import * as fs from "fs";
import * as path from "path";
import {ImagingBase} from "./imaging-base";
import {
    ConvertImageRequest, CreateConvertedImageRequest,
    ImagingApi,
} from "@asposecloud/aspose-imaging-cloud";

const ImageFileName = "example_image.wmf";
const ImagesFolder = "ExampleImages";
const CloudFolder = "CloudImages";
const OutputFolder = "Output";

// Get ClientId and ClientSecret from https://dashboard.aspose.cloud/ 
// or use on-premise version (https://docs.aspose.cloud/imaging/getting-started/how-to-run-docker-container/)
const api = new ImagingApi(clientSecret, clientId, "https://api.aspose.cloud");

/**
* Convert an image to another format.
*/
public async ConvertImageFromStorage() {

    const localInputImage = fs.readFileSync(path.join(ImagesFolder, ImageFileName));
    const uploadFileRequest = new UploadFileRequest({path: path.join(CloudFolder, imageName), file: image});
    const result = await this.api.uploadFile(uploadFileRequest);
    if (result.errors.length > 0)
        console.log(`Uploading errors count: ${result.errors.length}`

    // Please refer to https://docs.aspose.cloud/imaging/supported-file-formats/#convert
    // for possible output formats
    const format = "emz";
    const folder = this.CloudFolder; // Input file is saved at the desired folder in the storage
    const storage = undefined; // Cloud Storage name

    const request = new ConvertImageRequest({name: ImageFileName, format, folder, storage}); 
    const convertedImage = await this.api.convertImage(request);

    // Save the image file to output folder
    const convertedImageName = ImageFileName.substr(0, ImageFileName.lastIndexOf(".")) + "emz";
    const filePath = path.resolve(path.join(OutputFolder, convertedImageName));
    fs.writeFile(filePath, convertedImage, (err) => {
        if (err) {
            throw err;
            }
    });
}

/**
* Convert an image to another format. Image data is passed in a request stream.
*/
public async CreateConvertedImageFromRequest() {

    // Please refer to https://docs.aspose.cloud/imaging/supported-file-formats/#convert
    // for possible output formats
    const format = "emz";
    const outPath = undefined; // Path to updated file (if this is empty, response contains streamed image)
    const storage = undefined; // Cloud Storage name

    const inputStream = fs.readFileSync(path.resolve(ImagesFolder, ImageFileName));
    const request = new CreateConvertedImageRequest({imageData: inputStream, format, outPath, storage});
    const convertedImage = await this.api.createConvertedImage(request);

    // Save the image file to output folder
    const convertedImageName = ImageFileName.substr(0, ImageFileName.lastIndexOf(".")) + "emz";
    const filePath = path.resolve(path.join(OutputFolder, convertedImageName));
    fs.writeFile(filePath, convertedImage, (err) => {
        if (err) {
            throw err;
            }
    });
}