// NG imports
import { Component, OnInit, Inject, Optional } from '@angular/core'

// Material
import { MAT_DIALOG_DATA } from '@angular/material'

import { Subscription } from 'rxjs'

// Module Services
import { StatusService }  from '../../services/svc.status'


// Interfaces
interface Comment {
    entity_id: string;
    quote_id: string;
    status: string;
    created_by: {
        id: string;
        username: string;
        bus: string;
        retailer: string;
    };
    created_at: string;
    comment: string;
}

interface StatusCode {
    value: string;
    label: string;
}

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

export class StatusComponent {

    // ---- Variables ---- \\
    // Data
    comments: Comment[]
    message: string
    status_codes: StatusCode[]
    current_status: string

    // Logic
    errorMessage: string
    errorMessageTimout

    // Subscriptions
    private _subscriptions = new Subscription()


    constructor(
        @Optional() @Inject(MAT_DIALOG_DATA) public data: any,
        private _status: StatusService
    ) {
        this._subscriptions.add(
            this._status.comments$.subscribe((resp: any) => {
                
                console.log('sub response', resp)
                if(!!resp.errorMessage) {
                    console.error('could not set comments: ', resp.errorMessage)
                }
                else {
                    this.comments = resp
                }
            })
        )
    }


    // ---- Lifecycle hooks ---- \\
    ngOnInit() {
        this.getCurrentStatus()
        this.getStatusCodes()
        this.getComments()
    }


    ngOnDestroy() {
        this._subscriptions.unsubscribe()
    }


    // ---- Functions ---- \\

    /**
     * Simple submit function
     */
    submitComment() {
        this.addComment(this.message)
    }



    /**
     * Set statuscode to selected status. 
     * Show error if quote_id is missing
     * 
     * @param status 
     */
    setStatus(status: string) {
        
        // Check for quote id
        if(!!this.data && this.data.quote_id) {            
            this._status.setStatus(this.data.quote_id, status).subscribe((resp) => {
                if(resp.status === 'success') {
                    // We good :)
                }
                else if(resp.status === 'error') {
                    this.showErrorMessage('an error occured, please try again')
                }
            })
        }
        else {
            console.error('cannot set status, missing quote_id')
            this.showErrorMessage('an error occured, please try again')
        }
    }



    /**
     * Get status codes
     */
    getStatusCodes() {
        this._status.getStatusCodes().then((resp: StatusCode[]) => {
            this.status_codes = resp
        })
    }


    /**
     * Get the current status for quote
     */
    getCurrentStatus() {
        if(!!this.data && this.data.quote_id) {
            this._status.getStatusCode(this.data.quote_id).subscribe((resp) => {
                if(resp.status && resp.status === 'success') {
                    this.current_status = resp.data.code
                }
                else {
                    this.showErrorMessage('an error occured: could not get current status')
                }
            })
        }
    }




    /**
     * Add new comment to the quote and clear 
     * 
     * @param message 
     */
    addComment(message: string) {
        let errorFlag = false

        // Validate message
        if(!message || message.length <= 0) {
            errorFlag = true
            this.showErrorMessage('you cannot submit an empty message')
        }

        // Check for errors before proceding
        if(!errorFlag) {

            // Check for quote id
            if(this.data.quote_id) {            
                this._status.setComment(this.data.quote_id, message).subscribe((resp: any) => {
    
                    // reset message field on success or show error message
                    if(resp.status === 'success') {
                        this.message = ''
                    }
                    else if(resp.status === 'error') {
                        this.showErrorMessage('an error occured, please try again')
                    }
                })
            }
            else {
                console.error('cannot add comment, missing quote_id')
                this.showErrorMessage('an error occured, please try again')
            }
        }
    }


    /**
     * Send a request to get comments and update observable
     */
    getComments() {
        if(!!this.data && this.data.quote_id) {
            this._status.getComments(this.data.quote_id)
        }
        else {
            console.error('cannot get comments, missing quote_id')
        }
    }






    /**
     * Add en error message and clear it again after a bit of time
     * @param message 
     */
    private showErrorMessage(message: string) {
        this.errorMessage = ''
        this.errorMessage = message

        // reset error message
        clearTimeout(this.errorMessageTimout)
        this.errorMessageTimout = setTimeout(() => {
            this.errorMessage = ''
        }, 4000)
    }

}
