import { Component, OnInit, HostListener } from '@angular/core';
import { HitAWodService } from 'src/app/services/hit-a-wod.service';
import { Plan } from 'src/app/models/plan.model';
import { RegisterService } from 'src/app/services/register.service';
import { Router } from '@angular/router';
import { RegisterResponse } from 'src/app/models/register-response.model';
import { map } from 'rxjs/operators';
import { UserService } from 'src/app/services/user.service';
import { TokenService } from 'src/app/services/token.service';
import { AuthenticationService } from 'src/app/services/authentication.service';
import { environment } from 'src/environments/environment';

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

  //loading flags
  loadingPlans:boolean = true;
  loadingLegal:boolean = true;

  //error flags
  error:boolean = false;
  error_text:string;

  //data attributes
  plans:Plan[];
  selected_plan:Plan;
  basic_legal:any[];
  accept_legal:boolean = false;

  //register flags
  registering:boolean = false;
  registering_company:boolean = false;
  registering_payment_method:boolean = false;
  registering_paying:boolean = false;
  registerResponse:RegisterResponse;
  register_payment_method_url = environment.baseServerUrl;
  registering_error = false;
  registering_error_text:string;

  //finish flags
  finish:boolean = false;

  constructor(public api:HitAWodService,
              private registerService:RegisterService,
              private router:Router,
              private userService:UserService,
              private token:TokenService,
              private auth:AuthenticationService) { }

  ngOnInit(): void {
    //this.initFakeServiceData();
    this.registerService.setStep(4);
    if(!this.boxValid()) {
      this.router.navigate(["/register", "box"]);
    }
    this.fetchPlans();
    this.fetchLegal();
  }

  selectPlan(p:Plan) {
    this.selected_plan = p;
    this.registerService.request.plan_id = p.id;
  }

  register() {
    this.registering = true;
    this.registering_company = true;

    //1. Crear companyia
    this.api.createCompany(this.registerService.request).pipe(
      map(response => {
        //Ens loguejem dins angular
        //response.user.user_subscriptions = [ response.user_subscription ];
        //his.userService.setUser(response.user);
        this.token.handle(response.token);
        //this.auth.changeAuthStatus(true);
        return response;
      })
    ).subscribe(
      data => {
        //2. Guardar payment method
        this.registerResponse = data;
        this.registering_company = false;
        this.registering_payment_method = true;
      },
      error => {
        this.registering_company = false;
        this.registering_error = true;
        this.registering_error_text = "Se ha producido un error: " + error.message;
      }
    );
  }

  @HostListener('window:message',['$event'])
  onIframeMessage(e) {
    if (e.origin==this.register_payment_method_url) {
      if(e.data.status=='success') {
        //3. Pay
        this.registering_payment_method = false;
        this.registering_paying = true;
        this.api.putSubscriptionPay(this.registerResponse.subscription.id.toString()).subscribe(
          data => {
            this.registering = false;
            this.finish = true;
          },
          error => {
            this.registering_paying = false;
            this.registering_error = true;
            this.registering_error_text = "Se ha producido un error: " + error.message;
          }
        );
      }
      else if(e.data.status=='error') {
        this.registering_payment_method = false;
        this.registering_error = true;
        this.registering_error_text = "Se ha producido un error: " + e.data.message;
      }
    }
  }


  login() {
    this.auth.login(this.registerService.request.owner.email, this.registerService.request.owner.password).subscribe(
      data => {
        this.router.navigate(["/admin", "dashboard"]);
      }
    );
  }

  private fetchPlans() {
    const self = this;
    setTimeout(() => {
      self.plans = self.registerService.getPlans();
      self.loadingPlans = false;
      if(!self.plans) {
        self.error = true;
        self.error_text = "No se han podido obtener los planes. Inténtalo de nuevo más tarde.";
      }
    }, 1500);
  }

  private fetchLegal() {
    this.api.getAvisoLegalBasico().subscribe(
      data => {
        this.basic_legal = data.data;
        this.loadingLegal = false;
      },
      error => {
        this.loadingLegal = false;
        this.error = true;
        this.error_text = "No se ha podido obtener la política de privacidad. Inténtalo de nuevo más tarde";
      }
    );
  }

  private boxValid() {
    return  this.registerService.request.box.address != null &&
            this.registerService.request.box.city != null &&
            this.registerService.request.box.country != null &&
            this.registerService.request.box.county != null &&
            this.registerService.request.box.email != null &&
            this.registerService.request.box.name != null &&
            this.registerService.request.box.phone != null &&
            this.registerService.request.box.postal_code != null;
  }

  private initFakeServiceData() {
    this.registerService.request.company.address = "asdf";
    this.registerService.request.company.cif = "asdf";
    this.registerService.request.company.country = "ES";
    this.registerService.request.company.county = "ES";
    this.registerService.request.company.city = "ES";
    this.registerService.request.company.email = "company@bisual.net";
    this.registerService.request.company.fact_address_line1 = "asdf";
    this.registerService.request.company.fact_address_line2 = "asdf";
    this.registerService.request.company.fact_city = "asdf";
    this.registerService.request.company.fact_country_code = "ES";
    this.registerService.request.company.fact_county = "asdf";
    this.registerService.request.company.fact_name = "asdf";
    this.registerService.request.company.fact_serie = "asdf";
    this.registerService.request.company.fact_zipcode = "asdf";
    this.registerService.request.company.name = "asdf";
    this.registerService.request.company.phone = "asdf";
    this.registerService.request.company.slogan = "asdf";
    this.registerService.request.company.zipcode = "asdf";

    this.registerService.request.box.address = "asdf";
    this.registerService.request.box.city = "asdf";
    this.registerService.request.box.country = "ES";
    this.registerService.request.box.county = "asdf";
    this.registerService.request.box.email = "asdf";
    this.registerService.request.box.name = "asdf";
    this.registerService.request.box.phone = "asdf";
    this.registerService.request.box.postal_code = "asdf";

    this.registerService.request.owner.address = "asdf";
    this.registerService.request.owner.country = "ES";
    this.registerService.request.owner.email = "polribas114@gmail.com";
    this.registerService.request.owner.name = "asdf";
    this.registerService.request.owner.nif = "asdf";
    this.registerService.request.owner.password = "12345";
    this.registerService.request.owner.phone = "12345";
    this.registerService.request.owner.poblacio = "12345";
    this.registerService.request.owner.surnames = "12345";
    this.registerService.request.owner.zipcode = "12345";
    this.registerService.request.owner.date_of_birth = new Date();
  }

}
