import { Component, OnInit } from '@angular/core';
import { SubscriptionService } from 'src/app/services/subscription.service';
import { HitAWodService } from 'src/app/services/hit-a-wod.service';
import { Company } from 'src/app/models/company.model';
import { Box } from 'src/app/models/box.model';
import { UtilsService } from 'src/app/services/utils.service';
import { Pricing } from 'src/app/models/pricing.model';
import { Discount } from 'src/app/models/discount.model';
import * as countries_json from "../../../../assets/data/country_codes.json";


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

  company_id:number;
  company:Company;
  pricings:Pricing[];
  discounts:Discount[];

  countries:any = countries_json;

  //flags
  company_edit_mode:boolean = false;
  sync_fact_and_commercial_info:boolean = false;

  //edit box settings
  edit_box_settings_flag:boolean = false;
  edit_box_id:number;

  constructor(private subscriptionService:SubscriptionService,
              private api:HitAWodService,
              public utilsService:UtilsService) { }

  ngOnInit(): void {
    this.subscriptionService.currentSubscription.subscribe(
      data => {
        if(data!=null) {
          if(data.role.slug==="company_admin") {
            this.company_id = data.company.id;
            this.initData();
          }
          else {
            this.utilsService.showMessage(
              "warning", 
              "Necesitas ser administrador de empresa", 
              "Tienes seleccionada una suscripción que no es de administrador de empresa. Por favor, selecciona una suscripción válida."
            );
          }
        }
      }
    );
  }

  /**
   * PRICINGS
   */
  addNewPricing() {
    this.pricings.unshift(new Pricing());
  }

  savePricing(p:Pricing) {
    if(p.id!=null) {
      //actualitzar
      p.company_id = this.company_id;
      this.api.putPricing(p).subscribe(
        data => {
          this.pricings = null;
          this.fetchCompanyPricings();
        }
      );
    }
    else {
      //guardar
      p.company_id = this.company_id;
      this.api.postPricing(p).subscribe(
        data => {
          this.pricings = null;
          this.fetchCompanyPricings();
        }
      );
    }
  }

  deletePricing(p:Pricing) {
    if(confirm("¿Estás seguro que quieres eliminar esta tarifa? Si hay alguna suscripción asociada a esta tarifa ya no se podrá borrar.")) {
      this.api.deletePricing(p.id.toString()).subscribe(
        data => {
          this.pricings = null;
          this.fetchCompanyPricings();
        }
      );
    }
  }

  toggleBoxIdFromPricing(val:boolean, p:Pricing, id:number, i:number) {
    //la i es l'index dels pricings
    if(val!=null) {
      const index = p.box_ids.indexOf(id);
      if(val==true && index==-1) {
        p.box_ids.push(id);
      } 
      else {
        p.box_ids.splice(index, 1)
      }
    }

    this.pricings[i] = p;
  }

  /**
   * COMPANY
   */
  toggleSyncFlag(val:boolean) {
    if(val) {
      this.company.fact_address_line1 = this.company.address;
      this.company.fact_address_line2 = null;
      this.company.fact_city = this.company.city;
      this.company.fact_country_code = this.company.country;
      this.company.fact_county = this.company.county;
      this.company.fact_zipcode = this.company.zipcode;
    }

    this.sync_fact_and_commercial_info = val;
  }

  uploadCompanyImage(files:FileList) {
    const file:File = files.item(0);
    this.api.uploadCompanyProfileImage(this.company_id.toString(), file).subscribe(
      data => {
        this.company.logo_url = data.logo_url;
      }
    );
  }

  updateCompany() {
    this.company_edit_mode = false;
    this.api.updateCompany(this.company_id, this.company).subscribe(
      data => {
        this.company = data;
      }
    );
  }

  /**
   * BOXES
   */
  addNewBox() {
    this.company.boxes.unshift(new Box());
  }

  saveBox(b:Box) {
    if(b.id!=null) {
      //actualitzar
      b.company_id = this.company_id;
      this.api.putBox(b).subscribe(
        data => {
          this.company.boxes = null;
          this.fetchCompany();
        }
      );
    }
    else {
      //guardar
      b.company_id = this.company_id;
      this.api.postBox(b).subscribe(
        data => {
          this.company.boxes = null;
          this.fetchCompany();
        }
      );
    }
  }

  deleteBox(b:Box) {
    if(confirm("¿Estás seguro que quieres eliminar este box? Si hay alguna información asociada a este box no se podrá borrar.")) {
      this.api.deleteBox(b.id.toString()).subscribe(
        data => {
          this.company.boxes = null;
          this.fetchCompany();
        }
      );
    }
  }

  /**
   * DISCOUNTS
   */
  addNewDiscount() {
    this.discounts.unshift(new Discount());
  }

  saveDiscount(d:Discount) {
    if(d.id!=null) {
      //actualitzar
      d.company_id = this.company_id;
      this.api.putDiscount(d).subscribe(
        data => {
          this.discounts = null;
          this.fetchCompanyDiscounts();
        }
      );
    }
    else {
      //guardar
      d.company_id = this.company_id;
      this.api.postDiscount(d).subscribe(
        data => {
          this.discounts = null;
          this.fetchCompanyDiscounts();
        }
      );
    }
  }

  deleteDiscount(d:Discount) {
    if(confirm("¿Estás seguro que quieres eliminar este descuento? Si hay alguna información asociada a este descuento no se podrá borrar.")) {
      this.api.deleteDiscount(d.id.toString()).subscribe(
        data => {
          this.discounts = null;
          this.fetchCompanyDiscounts();
        }
      );
    }
  }

  private initData() {
    this.fetchCompany();
    this.fetchCompanyPricings();
    this.fetchCompanyDiscounts();
  }

  private fetchCompany() {
    this.api.company(this.company_id).subscribe(
      data => {
        this.company = data;
        this.initSyncCompanyInfoFlag();
      }
    );
  }

  private fetchCompanyPricings() {
    this.api.companyPricings(this.company_id).subscribe(
      data => this.pricings = data.data
    );
  }

  private fetchCompanyDiscounts() {
    this.api.companyDiscounts(this.company_id).subscribe(
      data => this.discounts = data.data
    );
  }

  private initSyncCompanyInfoFlag() {
    this.sync_fact_and_commercial_info =  this.company.address == this.company.fact_address_line1 &&
                                          (!this.company.fact_address_line2 || this.company.fact_address_line2=="") &&
                                          this.company.city == this.company.fact_city &&
                                          this.company.fact_country_code == this.company.country &&
                                          this.company.county == this.company.fact_county &&
                                          this.company.zipcode == this.company.fact_zipcode;
  }

}
