import { AxiosResponse } from 'axios';
import { PurchaseContentCommand } from '../commands/content/purchaseContentCommand';
import { WatchNonstopResult } from '../models/content/watchNonstopResult';
import { AbpResponse } from '../models/http/abpResponse';
import { ResultBase } from '../models/http/resultBase';
import { Purchase } from '../models/purchases/purchase';
import { BaseService } from './abstract/baseService';
import connectService from './connectService';
import contentService from './contentService';
import dataService from './dataService';

class PurchaseService extends BaseService {

    public static sharedInstance = new PurchaseService();

    protected logTag: string = 'PurchaseService';

    public async purchaseContent(contentId: string, price: number, onError: (rawResponse: AxiosResponse<AbpResponse<ResultBase>> | null) => void): Promise<Purchase | null> {
        const purchaseContentCommand = new PurchaseContentCommand(contentId, price, onError);
        const purchaseContentResult = await dataService.executeCommand(purchaseContentCommand);
        if (purchaseContentResult) {
            this.addPurchase(purchaseContentResult.contentId);
        }
        return purchaseContentResult;
    }

    public async shouldWatchNonstop(contentId: string): Promise<WatchNonstopResult | null> {
        const content = await contentService.getContent(contentId);
        const result = new WatchNonstopResult();
        result.shouldWatchNonstop = content ? content.isPurchased : false;
        return result;
    }

    public getContentNonstopStatus(contentId: string): WatchNonstopResult {
        const result = new WatchNonstopResult();
        if (connectService.activePurchases && connectService.activePurchases.length) {
            const activePurchases = connectService.activePurchases;
            result.shouldWatchNonstop = activePurchases.includes(contentId);
        }
        return result;
    }

    private addPurchase(contentId: string): void {
        const activePurchases = connectService.activePurchases || [];
        activePurchases.push(contentId);
        connectService.activePurchases = activePurchases;
    }
}

export default PurchaseService.sharedInstance as PurchaseService;