package com.mycompany.update;

import com.github.sardine.DavResource;
import com.github.sardine.Sardine;
import com.github.sardine.SardineFactory;
import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;

public class functions {
    String ip_server_address = "https://webdav.yandex.ru/";
    String server_username = "ayrong.vcbks";
    String server_user_password = "nxxswdzfoiulwate";
    Sardine sardine = SardineFactory.begin(server_username, server_user_password);
    
    Map<String, Long> map_1 = new HashMap<String, Long>();
    
    Map<String, Long> map_2 = new HashMap<String, Long>();
    
    public boolean successful_update = true;
    
    public boolean show_update_information = false;
    
    public void downloading(String path_to_server, String path_to_user, String name_file) throws IOException
    {
        InputStream input_stream = sardine.get(ip_server_address + path_to_server.replace(" ", "%20") + "/" + name_file.replace(" ", "%20"));
        File targetFile = new File(path_to_user + "/" + name_file);
        OutputStream outStream = new FileOutputStream(targetFile);
        byte[] buffer = new byte[8 * 1024];
        int bytesRead;
        while ((bytesRead = input_stream.read(buffer)) != -1)
        {
          outStream.write(buffer, 0, bytesRead);
        }

        List<DavResource> server_files2 = sardine.list(ip_server_address + path_to_server);

        input_stream.close();
        outStream.close();
        
        //System.out.println("path_to_server = " + path_to_server);
        //System.out.println("name_file = " + name_file);
        
        //last date
        File targetFile2 = new File(path_to_user + "/" + name_file);
        
        for (DavResource server_file2 : server_files2)
        {
            if(server_file2.getName().equals(name_file)) {
                
                //System.out.println("true = " + server_file2.getName() + " = " + name_file);
                //System.out.println("srv_time = " + server_file2.getModified().getTime());
                targetFile2.setLastModified(server_file2.getModified().getTime());
            }
            //else {
                //System.out.println("false = " + server_file2.getName() + " = " + name_file);
            //}
        }
    }
    
    public void test_1(String path_to_server, String path_to_user, String path_to_temp) throws IOException
    {
        List<DavResource> server_files = sardine.list(ip_server_address + path_to_server);
        
        boolean downloading_last_segment = false;
        
        for (DavResource server_file : server_files)
        {
            boolean download = true;
            
            File user_file = new File(path_to_user);
            File[] user_files = user_file.listFiles();
            
            String server_path_segments[] = path_to_server.split("/");
            String last_server_segment = server_path_segments[server_path_segments.length - 1].replace("%20", " ");
            
            if(!server_file.getName().equals(last_server_segment) || downloading_last_segment)
            {
                if(!server_file.isDirectory())
                {
                    for(int i=0; i < user_files.length; i++)
                    {
                        if(server_file.getName().equals(user_files[i].getName()) && server_file.getContentLength() == user_files[i].length() && server_file.getModified().getTime() == user_files[i].lastModified())
                        {
                            download = false;
                        }
                    }
                }
                else
                {
                    download = false;
                    
                    File creating_a_folder_user = new File(path_to_user + "\\" + server_file.getName());
                    creating_a_folder_user.mkdir();
                    
                    File creating_a_folder_temp = new File(path_to_temp + "\\" + server_file.getName());
                    creating_a_folder_temp.mkdir();
                    
                    test_1(path_to_server + "/" + server_file.getName().replace(" ", "%20"), path_to_user + "\\" + server_file.getName(), path_to_temp + "\\" + server_file.getName());
                }
            }
            else
            {
                download = false;
                
                if(downloading_last_segment)
                {
                    File creating_a_folder_user = new File(path_to_user + "\\" + server_file.getName());
                    creating_a_folder_user.mkdir();
                    
                    File creating_a_folder_temp = new File(path_to_temp + "\\" + server_file.getName());
                    creating_a_folder_temp.mkdir();
                    
                    test_1(path_to_server + "/" + server_file.getName().replace(" ", "%20"), path_to_user + "\\" + server_file.getName(), path_to_temp + "\\" + server_file.getName());
                    
                    downloading_last_segment = false;
                }
                else
                {
                    downloading_last_segment = true;
                }
            }
            
            if(download) 
            {
                map_1.put(path_to_server + "/" + server_file.getName(), server_file.getContentLength());
                
                System.out.print(".");
                
                downloading(path_to_server, path_to_temp, server_file.getName());
                
                File creating_a_file_temp = new File(path_to_temp + "\\" + server_file.getName());
                
                map_2.put(path_to_server + "/" + server_file.getName(), creating_a_file_temp.length());
            }
        }
    }
    
    public void test_2() throws IOException
    {
        if(map_1.size() == map_2.size())
        {
            Iterator iterator_1 = map_1.entrySet().iterator();
            
            while(iterator_1.hasNext())
            {
                Map.Entry pair_1 = (Map.Entry)iterator_1.next();
                
                Iterator iterator_2 = map_2.entrySet().iterator();
                
                while(iterator_2.hasNext())
                {
                    Map.Entry pair_2 = (Map.Entry)iterator_2.next();
                    if(pair_1.getKey().equals(pair_2.getKey()) && !pair_1.getValue().equals(pair_2.getValue()))
                    {
                        successful_update = false;
                    }
                    
                    if(pair_1.getKey().equals(main.path_to_server + "/" + "Обновление программного обеспечения.txt") && pair_2.getKey().equals(main.path_to_server + "/" + "Обновление программного обеспечения.txt")  && successful_update && !pair_1.getValue().toString().equals("0"))
                    {
                        show_update_information = true;
                    }
                }
                
                iterator_1.remove();
            }
        }
        else
        {
            successful_update = false;
        }
    }
    
    public void copying(String path_to_temp, String path_to_user) throws IOException
    {
        File src_dir = new File(path_to_temp);
        
        File dest_dir = new File(path_to_user);
        
        FileUtils.copyDirectory(src_dir, dest_dir);
    }
    
    public void show_update_information() throws IOException
    {
        File information = new File("Обновление программного обеспечения.txt");
        
        if(!Desktop.isDesktopSupported())
        {
            return;
        }
        
        Desktop desktop = Desktop.getDesktop();
        
        if(information.exists())
        {
            desktop.open(new File("Обновление программного обеспечения.txt"));
        }
    }
}
