/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.triz.util;

import java.awt.Color;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.faces.FacesException;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

/**
 *
 * @author abder_000
 */
@Service()
public class UtilFile {

    public String getVirtualFileUrl(String dossier, String id) {
        System.out.println(" TestOf Access : "+id);
        if (id != null) {
            if (!(id.endsWith(".png") | id.endsWith(".PNG") | id.endsWith(".jpg") | id.endsWith(".JPG") | id.endsWith(".jpeg") | id.endsWith(".JPEG") | id.endsWith(".jfif") | id.endsWith(".JFIF"))) {
                id = id + ".png";
            }
        }
        String imageBaseUrl = getImageApplicationUri();
        String url = imageBaseUrl + "/." + dossier + "/" + id;
        System.out.println(" TestOf Access2 : "+url);
        return url;

    }
    
    public String getVirtualFileUrlDoc(String dossier, String id) {
        String racine = new UtilGetParametre().getPropertyByKey(UtilGetParametre.TRIZDISTRIBUTION_DOSSIER_CHEMAIN);
        String imageBaseUrl = getImageApplicationUri();
        //String homeBaseDirectory = getDirectoryName();
        //System.out.println("getVirtualFileUrl :"+imageBaseUrl+"/.trizDistribution" + "/." + dossier + "/" + id);
//        String url = imageBaseUrl + "/.trizDistribution" + "/." + dossier + "/" + id;
        String url = imageBaseUrl + "/." + dossier + "/" + id;
        System.out.println("TestOfLink : "+ url);
        return url;

    }

    
    public String getVirtualFileUrl(String dossier, String repertoire, String id) {
        String imageBaseUrl = getImageApplicationUri();
        //String homeBaseDirectory = getDirectoryName();
        //System.out.println("getVirtualFileUrl :"+imageBaseUrl+"/.trizDistribution" + "/." + dossier + "/" + id);
//        String url = imageBaseUrl + "/.trizDistribution" + "/." + dossier + "/" + repertoire + "/" + id;
        String url = imageBaseUrl + "/." + dossier + "/" + repertoire + "/" + id;
        return url;
    }

    public static String getDirectoryHome() {
        String racine = new UtilGetParametre().getPropertyByKey(UtilGetParametre.TRIZDISTRIBUTION_DOSSIER_CHEMAIN);
        if (racine == null) {
            racine = System.getProperty("user.home");
        }
        File file = new File(racine + File.separator + ".trizDistribution" );

        //System.err.println("file :" + file.getPath());
        file.mkdirs();

        return racine + File.separator + ".trizDistribution";

    }

    public static String getDirectoryName(String dossier) {
        String racine = new UtilGetParametre().getPropertyByKey(UtilGetParametre.TRIZDISTRIBUTION_DOSSIER_CHEMAIN);
        if (racine == null) {
            racine = System.getProperty("user.home");
        }
        File file = new File(racine + File.separator + ".trizDistribution" + File.separator + "." + dossier);

        //System.err.println("file :" + file.getPath());
        file.mkdirs();

        return racine + File.separator + ".trizDistribution" + File.separator + "." + dossier;

    }

    public static String getDirectoryMobileName(String dossier, String racine) {
        //String racine = new UtilGetParametre().getPropertyByKey(UtilGetParametre.TRIZDISTRIBUTION_DOSSIER_MOBILE_CHEMAIN);
        
        return racine + "/" + ".trizDistribution" + "/" + "." + dossier /*+ "/"*/; 

    }

    public static String getDirectoryMobileNameWithPath(String dossier) {
        String racine = new UtilGetParametre().getPropertyByKey(UtilGetParametre.TRIZDISTRIBUTION_DOSSIER_MOBILE_CHEMAIN);
        
        return /*racine + "/" +*/ ".trizDistribution" + "/" + "." + dossier /*+ "/"*/; 

    }

    public static String compressionImageJPG(String chemain) {
//        System.out.println("compressionImageJPG :"+ chemain);
        String newChemain = chemain;
        if (chemain == null) {
            return null;
        }
        if (!(chemain.endsWith(".jpg") | chemain.endsWith(".JPG") | chemain.endsWith(".jpeg") | chemain.endsWith(".JPEG") | chemain.endsWith(".png") | chemain.endsWith(".PNG") | chemain.endsWith(".jfif") | chemain.endsWith(".JFIF"))) {
            return null;
        }
        if (chemain.endsWith(".png") | chemain.endsWith(".PNG")) {
            BufferedImage bufferedImage;
            newChemain = chemain.substring(0, chemain.length()-4) + "_conv.jpg";
            try {

                //read image file
                bufferedImage = ImageIO.read(new File(chemain));

                // create a blank, RGB, same width and height, and a white background
                BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
                        bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
                newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);

                // write to jpeg file
                ImageIO.write(newBufferedImage, "jpg", new File(newChemain));
                chemain = newChemain;
                newChemain = chemain + ".jpg";
                System.out.println("Done");

            } catch (IOException e) {

                e.printStackTrace();

            }
        }
        File imageFile = new File(chemain);
        newChemain = chemain.substring(0, chemain.length()-(imageFile.getName().length()))+ "red_" + imageFile.getName();
        File compressedImageFile = new File(newChemain);
        String file_reselt = imageFile.getName();
        int max = 0;
        float reduction = 1;
        try {
            BufferedImage bi = ImageIO.read(imageFile);
            System.out.println("Traitement de : " + chemain);
            max = bi.getWidth();

            System.out.println("max de : " + max);
            if (bi.getHeight() > max) {
                max = bi.getHeight();
            }
            System.out.println("max de : " + max);

            if (max > 300) {
                System.out.println("reduction ");
                reduction = (float) 2000 / max;

                int width = (int) (bi.getWidth() * reduction);
                int height = (int) (bi.getHeight() * reduction);
                System.out.println("width de : " + bi.getWidth());
                System.out.println("height de : " + bi.getHeight());

                System.out.println("width de : " + width);
                System.out.println("height de : " + height);
                System.out.println("reduction de : " + reduction);
                BufferedImage biNew = new BufferedImage(width, height, bi.getType());
                AffineTransform tx = new AffineTransform();
                tx.scale(reduction, reduction);
//                tx.setToRotation(0);
                AffineTransformOp op = new AffineTransformOp(tx,
                        AffineTransformOp.TYPE_BILINEAR);
                bi = op.filter(bi, biNew);
                ImageIO.write(bi, "JPG", compressedImageFile);
                System.out.println("saving de : " + newChemain);
                file_reselt = compressedImageFile.getName();
            }
        } catch (Exception e) {
            System.out.println("ERROR -- le fichier" + chemain + " n'est pas une image");
            e.printStackTrace();
        }
        return file_reselt;
//        return chemain;
    }
    // CREATE A MATRIX FOR THE MANIPULATION
//Matrix matrix = new Matrix();
//// RESIZE THE BIT MAP
//matrix.postScale(reduction, reduction);
//
//ExifInterface exif = null;
//try {
//    exif = new ExifInterface(new File(chemain).getAbsolutePath());
//    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
//    Log.e("ppp", "Exif: " + orientation);
//
//
//    if (orientation == 6) {
//        matrix.postRotate(90);
//    } else if (orientation == 3) {
//        matrix.postRotate(180);
//    } else if (orientation == 8) {
//        matrix.postRotate(270);
//    }
//
//
//} catch (IOException e) {
//    Log.e("ppp", " exif no file:");
//    e.printStackTrace();
//}

    public static String getFilePath(String dossier, String fileName) {

        //System.out.println("---------------new file path call-----------");
        String filePath = getDirectoryName(dossier) + File.separator + fileName;

        //System.out.println("storing files in dicrecoty :"+filePath);
        return filePath;
    }

    public static String getFilePath(String dossier, String repertoir, String fileName) {

        //System.out.println("---------------new file path call-----------");
        String filePath = getDirectoryName(dossier) + File.separator + repertoir + File.separator + fileName;

        //System.out.println("storing files in dicrecoty :"+filePath);
        return filePath;
    }

    public String getImageApplicationUri() {
        try {

            FacesContext ctxt = FacesContext.getCurrentInstance();
            ExternalContext ext = ctxt.getExternalContext();
            URI uri = new URI(ext.getRequestScheme(),
                    null, ext.getRequestServerName(), ext.getRequestServerPort(),
                    "/images", null, null);
            return uri.toASCIIString();

        } catch (URISyntaxException e) {
            throw new FacesException(e);
        }
    }
    
    public static String getDirectory() {
        String racine = new UtilGetParametre().getPropertyByKey(UtilGetParametre.TRIZDISTRIBUTION_DOSSIER_CHEMAIN);
        if (racine == null) {
            racine = System.getProperty("user.home");
        }
        File file = new File(racine + File.separator + ".trizDistribution" );

        //System.err.println("file :" + file.getPath());
        file.mkdirs();

        return racine + File.separator + ".trizDistribution" ;

    }
    
    public static String getURLPath(String ip){
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();
        ip = ip+ ":"+request.getLocalPort()+request.getContextPath();
        System.out.println("getURLPath:"+ip);
        return ip;
    }
    
    

}
