import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { DataService } from '../data.service';
import { environment } from '../../environments/environment';
import axios from 'axios';

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

  ready = false;

  line1: any;
  line2: any;
  line3: any;
  line_number1: any;
  line_number2: any;
  line_number3: any;

  BASE_URL = environment.BASE_URL;

  constructor(
    private activated_route: ActivatedRoute,
    private toastr: ToastrService,
    private data: DataService
  ) { }

  ngOnInit(): void {
    this.activated_route.params.subscribe((params) => {
      if(Object.keys(params).length > 0) {
        this.ready = true;
        this.line_number1 = params['line1'];
        this.line_number2 = params['line2'];
        this.line_number3 = params['line3'];
        axios({
          method: 'post',
          url: this.BASE_URL + '/get_instance', 
          params: {
            line1: this.line_number1,
            line2: this.line_number2,
            line3: this.line_number3
        }})
        .then((ting) => {
          this.line1 = ting.data.line1;      
          this.line2 = ting.data.line2;      
          this.line3 = ting.data.line3;      
        })
        .catch((e) => {
          console.log(e);
          this.toastr.error('Server Error!', e);
        });
      }
    });

  }

  async save_instance() {
    try {
      await this.data.set_item({
        line1: this.line1,
        line2: this.line2,
        line3: this.line3,
        line_number1: this.line_number1,
        line_number2: this.line_number2,
        line_number3: this.line_number3
      });
      this.toastr.success('Instance Saved !', "");
    } catch (e) {
      console.error(e);
      this.toastr.error('Unable to save instance !');
    }
  }

}
