import request = require('request');
import { FastlyServices, FastlyServicesResponse } from './interfaces/services';
import { FastlyStatsResponse } from './interfaces/stats';

export class Fastly {
    apiKey: string;
    ready: Promise<{}>;
    regions: string[];
    services: FastlyServices;

    constructor(apiKey: string) {
        this.apiKey = apiKey
        this.regions = [];
        this.services = {};

        this.ready = Promise.all([
            this.list_regions(),
            this.list_services()
        ])
    }

    public async regional_stats(): Promise<FastlyStatsResponse[]> {
        await this.ready;
        return Promise.all(this.regions.map(async (r) => {
            return (this.get('/stats?by=minute&from=10+minutes+ago&region=' + r)) as Promise<FastlyStatsResponse>;
        }));
    }
    
    private async list_regions() {
        this.regions = (await this.get('/stats/regions')).data;
    }

    private async list_services() {
        (await this._list_services()).data.map(async (s) => {
            this.services[s.id] = s;
        });
    }

    private async _list_services(): Promise<FastlyServicesResponse> {
        return this.get('/services');
    }

    private async get(uri:string) {
        return new Promise<any>((resolve, reject) => {
            let headers = {
                'fastly-key': this.apiKey,
                'accept': 'application/json'
            }

            request({
                method: 'GET',
                url: 'https://api.fastly.com' + uri,
                headers: headers
            }, (err, response, body) => {
                if (response) {
                    let statusCode = response.statusCode as number;
                    if (!err && (statusCode < 200 || statusCode > 302))
                        err = new Error(body);
                    if (err) err.statusCode = statusCode;
                }

                if (err) reject(err);

                try {
                    resolve(JSON.parse(body));
                } catch (er) {
                    resolve(body);
                }
            });
        })
    }
}