import {Injectable} from '@angular/core';

@Injectable()
export class UtilService {

    startTime;
    stoppedStatus = true;

    constructor() {
    }

    /*
     * 生成uuid算法,碰撞率低于1/2^^122
     * @param x 0-9或a-f范围内的一个32位十六进制数
     */
    generateUUID() {
        let d = new Date().getTime();
        let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
            let r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
        return uuid;
    }

    /**
     * 计算程序执行时间
     * @type {{startTime: {}, timeSpan: number, start: Timer.start, stop: Timer.stop, getTimeSpan: Timer.getTimeSpan}}
     */

    start() {
        if (this.stoppedStatus) {
            this.startTime = new Date().getTime();
            this.stoppedStatus = false;
        }
    }

    pause() {
        let startTime = this.startTime;
        if (startTime) {
            let  t = new Date().getTime() - startTime;
            return t;
        } else {
            return -1;
        }
    };

    stop() {
        let startTime = this.startTime;
        if (startTime) {
            this.stoppedStatus = true;
            let  t = new Date().getTime() - startTime;
            return t;
        } else {
            this.stoppedStatus = true;
            return -1;
        }
    }

}
