
// Core imports
import { Component, OnInit } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router'

// Core Services


// Module Services
import { AcceptOfferService } from '../../services/svc.acceptOffer'
import { NgForm } from '@angular/forms';

/**
 * @name AcceptComponent
 * @description *watdo?*
 * @author *whodis?*
 * @since *wendis?*
 * @extends
 */
@Component({
    moduleId: module.id+ '',
    selector: 'accept-offer-accept',
    templateUrl: './template/t--accept.pug',
    styleUrls: ['sty.accept.scss']
})

export class AcceptComponent implements OnInit{

    // ---- Variables ---- \\
    offerId: string | boolean
    offerFound: boolean = true
    errorMessage: string = undefined
    contentBlock: HTMLElement | undefined = undefined
    constructor(
        private _route: Router,
        private _activatedRoute: ActivatedRoute,
        private _acceptService: AcceptOfferService
    ) { }


    // ---- Lifecycle hooks ---- \\
    ngOnInit() {

        // Gets the query parameter, and then returns the Offer Id based on the parameter
        this._activatedRoute.queryParams.take(1).subscribe((params) => {

            this._acceptService.getOffer(params.id).then((response) => {

                if(!!response.offer_id) {

                    this.offerFound = true
                }
                else {

                    this.offerFound = false
                    this.contentBlock = response.block
                }

                this.offerId = response.offer_id
            })

        })
    }


    // ---- Functions ---- \\
    submit(form: NgForm) {
        let formResult = form.value
        
        formResult.orderId = this.offerId
        this._acceptService.setOffer(formResult).then((response: any) => {

            if(!!response.data.errorMessage) {

                this.errorMessage = response.data.errorMessage
                
                setTimeout(() => {
                    this.errorMessage = undefined
                }, 3000)

            } else {

                this._route.navigate([response.data.url])
            }
        })
    }

}
