import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { HitAWodService } from 'src/app/services/hit-a-wod.service';
import { UserSubscription } from 'src/app/models/user-subscription.model';
import { Role } from 'src/app/models/role.model';
import { UtilsService } from 'src/app/services/utils.service';
import { SubscriptionSelection } from 'src/app/models/subscription-selection.model';
import { SubscriptionService } from 'src/app/services/subscription.service';
import { StripeUser } from 'src/app/models/stripe-user.model';
import { Pricing } from 'src/app/models/pricing.model';
import * as moment from 'moment';
import { BoxOrder } from 'src/app/models/box-order.model';
import { LinealChart } from 'src/app/models/Charts/lineal-chart.model';

@Component({
  selector: 'app-subscription-detail',
  templateUrl: './subscription-detail.component.html',
  styleUrls: ['./subscription-detail.component.css']
})
export class SubscriptionDetailComponent implements OnInit {

  id_user_subscription:string;
  us:UserSubscription;
  roles:Role[];
  subscription_selection:SubscriptionSelection;
  stripe_user:StripeUser;
  user_subscriptions:UserSubscription[];
  end_date_persistance:Date;
  now:Date = new Date();
  
  //renew section
  pricings:Pricing[];
  selected_pricing:Pricing;
  override:boolean;
  change_subscription_screen:boolean = false;
  renew_subscription_screen:boolean = false;
  next_period_date_end:Date;
  marcar_como_pagado:boolean = false;

  //Chart
  assists_chart: LinealChart;
  company_id:number;
  box_id:number;

  constructor(private activatedRoute:ActivatedRoute,
              private api:HitAWodService,
              public utilsService:UtilsService,
              private router:Router,
              private subscriptionService:SubscriptionService) {
                this.activatedRoute.params.subscribe(
                  data => {
                    this.id_user_subscription = this.activatedRoute.snapshot.paramMap.get("id");
                    this.subscription_selection = this.subscriptionService.currentSubscriptionValue;
                    this.fetchUserSubscription();
                    this.fetchRoles();
                    this.fetchPricings();
                    
                  }
                );
              }

  ngOnInit(): void {
    //this.id_user_subscription = this.activatedRoute.snapshot.paramMap.get("id");
    //this.subscription_selection = this.subscriptionService.currentSubscriptionValue;
    //this.fetchUserSubscription();
    //this.fetchRoles();
    //this.fetchPricings();
  }

  save() {
    this.api.putUserSubscription(this.us, this.us.box_ids[0].toString()).subscribe(
      data => {
        
      }
    );
  }

  toggleSubscriptionUnlimited() {
    if(this.us.end_date == null) {
      this.us.end_date = this.end_date_persistance;
      if(!this.us.end_date) this.us.end_date = new Date();
      this.setNextPeriodDateEnd();
    }
    else {
      this.us.end_date = null;
    }
  }

  processSubscriptionChange() {
    const start_date = moment(this.override ? new Date() : this.us.end_date);
    this.api.renewUserSubscription(this.us.id.toString(), {
      pricing_id: this.selected_pricing.id,
      role_id: this.us.role_id,
      user_id: this.us.user_id,
      renew: 0,
      start_date: start_date.format("YYYY-MM-DD"),
      payment_type_id: 2, //cash
      override: this.override ? 1 : 0,
      box_id: this.subscription_selection.level==="Box" ? this.subscription_selection.box.id : (this.us.box_orders.length > 0 ? this.us.box_orders[0].box_id : this.us.box_ids[0])
    }).subscribe(
      ([msg, s, bo]) => {
        if(this.marcar_como_pagado) {
          this.api.payUserSubscription(s.id.toString(), {
            start_date: start_date.format("YYYY-MM-DD HH:mm:ss"),
            box_id: this.subscription_selection.level==="Box" ? this.subscription_selection.box.id : (this.us.box_orders.length > 0 ? this.us.box_orders[0].box_id : this.us.box_ids[0]),
            payment_type_slug: "cash"
          }).subscribe(
            data => {
              this.router.navigate(['/admin', 'subscriptions', data.id]);
              this.change_subscription_screen = false;
            }
          );
        }
        else {
          this.router.navigate(['/admin', 'subscriptions', s.id]);
          this.change_subscription_screen = false;
        }
      }
    );
  }

  processSubscriptionRenew() {
    this.api.renewUserSubscription(this.id_user_subscription, {
      pricing_id: this.us.pricing_id,
      renew: 0,
      start_date: moment(this.override ? new Date() : this.us.end_date).format("YYYY-MM-DD"),
      payment_type_id: 2, //cash
      override: this.override ? 1 : 0,
      box_id: this.subscription_selection.level==="Box" ? this.subscription_selection.box.id : (this.us.box_orders.length > 0 ? this.us.box_orders[0].box_id : this.us.box_ids[0])
    }).subscribe(
      data => {
        if(this.marcar_como_pagado) {
          //paguem ara
          this.api.payUserSubscription(this.id_user_subscription, {
            box_id: this.subscription_selection.level==="Box" ? this.subscription_selection.box.id : (this.us.box_orders.length > 0 ? this.us.box_orders[0].box_id : this.us.box_ids[0]),
            payment_type_slug: "cash"
          }).subscribe(
            data => {
              this.fetchUserSubscription();
              this.renew_subscription_screen = false;
            }
          );
        }
        else {
          //paguem mes tard
          this.fetchUserSubscription();
          this.renew_subscription_screen = false;
        }
      }
    );
  }

  subscriptionHasAutomaticRenew():boolean {
    return  this.subscription_selection.company.is_stripe_active && 
            this.stripe_user?.is_stripe_active && 
            this.us.renew===true;
  }

  //cobrar un box order mes tard
  cobrar(bo:BoxOrder) {
    if(confirm("¿Quieres marcar este pedido como cobrado? Se generará una factura y se contabilizará como ingreso. Se renovará la suscripción.")) {
      this.api.payUserSubscription(this.id_user_subscription, {
        box_id: this.subscription_selection.level==="Box" ? this.subscription_selection.box.id : (this.us.box_orders.length > 0 ? this.us.box_orders[0].box_id : this.us.box_ids[0]),
        payment_type_slug: "cash"
      }).subscribe(
        data => {
          this.fetchUserSubscription();
          this.renew_subscription_screen = false;
        }
      );
    }
  }

  private fetchUserSubscription() {
    this.api.getUserSubscriptionById(this.id_user_subscription).subscribe(
      data => {
        this.us = data;
        this.end_date_persistance = this.us.end_date;
        this.fetchStripeUser();
        this.fetchOtherUserSubscriptions();
        this.fetchAssists();
        this.setNextPeriodDateEnd();
      }
    ); 
  }

  private fetchRoles() {
    this.api.getAllRoles().subscribe(
      data => {
        this.roles = data;
      }
    );
  }

  private fetchStripeUser() {
    this.api.getCompanyStripeUserByUserId(this.subscription_selection.company.id.toString(), this.us.user_id.toString()).subscribe(
      data => {
        this.stripe_user = data;
      }
    );
  }

  private fetchOtherUserSubscriptions() {
    this.api.getCompanyUserUserSubscriptions(this.subscription_selection.company.id.toString(), this.us.user_id.toString()).subscribe(
      data => {
        const data2:UserSubscription[] = data.data;
        this.user_subscriptions = data2.filter(us => us.id!=this.us.id);
      }
    );
  }

  private fetchPricings() {
    if(this.subscription_selection.level === "Company") {
      this.api.companyPricings(this.subscription_selection.company.id).subscribe(
        data => {
          this.pricings = data.data.filter((p:Pricing) => p.id!=this.us.pricing_id);
        }
      );
    }
    else if(this.subscription_selection.level === "Box") {
      this.api.getBoxPricings(this.subscription_selection.box.id.toString()).subscribe(
        data => {
          this.pricings = data.data.filter((p:Pricing) => p.id!=this.us.pricing_id);
        }
      );
    }
  }

  private fetchAssists() {
    this.assists_chart = null;
    this.subscriptionService.currentSubscription.subscribe( s => {
      if (s) {
        if (s.box) {
          this.company_id = s.box.company_id;
          this.box_id = s.box.id;
        } else {
          this.company_id = s.company.id;
          this.box_id = null;
        }
        this.api.getAssists(this.company_id, this.us.user_id, this.box_id).subscribe( a => {
          this.assists_chart = new LinealChart();
          this.assists_chart.showLegend = false;
          this.assists_chart.showXAxisLabel = false;
          this.assists_chart.showYAxisLabel = false;
          this.assists_chart.colorScheme.domain = this.utilsService.getColorsArray();
          this.assists_chart.results = a.chart;
        });
      }
    });
  }

  private setNextPeriodDateEnd() {
    this.next_period_date_end = moment(this.us.end_date).add(this.us.pricing.days, 'days').toDate();
  }

}
