package testgdz.online_cc;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
//import static java.lang.System.in;
import javax.imageio.ImageIO;
import java.util.Scanner;

public class ConvertImageFile {
    //глобальные переменные
   public static BufferedImage partOfImage;   //тут хранится обрезок
   public static BufferedImage newBufferedImage = null; //тут картинка
   public static String image_patch = null; //тут адрес изначальной картинки
   public static String output_dir = null; //тут адрес выходной папки
   public static int part_counter = 0; //тут номер куска
   public static int part_height = 0; // тут вертикальный размер куска
   public static int part_width = 0; // тут горизонтальный размер куска
   
   public static void main(String[] args) throws IOException {        
       	
       
        
	
	  //ввод пути к картинке (\/) :) (\/)
          Scanner cinput = new Scanner(System.in);  //создаём ввод
          System.out.println("Введите полный путь к вводной картинке");
          image_patch = cinput.nextLine();
          System.out.println("Введите полный путь вывода");
          output_dir = cinput.nextLine();          
          System.out.println("Введите высоту");
          part_height = cinput.nextInt();
          System.out.println("Введите ширину");
          part_width = cinput.nextInt();
          
          
	  convertAndCutImage();
          
	  System.out.println("Готово!");

	

   }
   public static void convertAndCutImage() throws IOException{
       int imgHeight = 0;
       BufferedImage bufferedImage = null;
       try {
           //Считываем изображение в буфер
        bufferedImage = ImageIO.read(new File(image_patch));
                 
	  // создаем пустое изображение RGB, с той же шириной высотой и белым фоном
	  newBufferedImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
	  newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);

	  // записываем новое изображение в формате jpg
	  ImageIO.write(newBufferedImage, "jpg", new File(output_dir + "\\converted.jpg"));
          } catch (IOException e) {
	  e.printStackTrace();
	  }
          // делаем нарезку          
          while(!(imgHeight >= bufferedImage.getHeight()))
          {
             widthCutter(imgHeight);
             imgHeight = imgHeight + part_height;
          }
       
   }
 
   public static int heightRest(int y_pos){ // проверка по высоте
       if(newBufferedImage.getHeight() -  y_pos <= 0){
           return 0;
       }
       else{
           if(newBufferedImage.getHeight() - y_pos < part_height){
               return newBufferedImage.getHeight() - y_pos;
           }
           else{
               return part_height;
           }
       }
   }
   
   
   
   public static int widthRest(int x_pos){  //проверка по ширине
       if(newBufferedImage.getWidth() -  x_pos <= 0){
           return 0;
       }
       else{
            if(newBufferedImage.getWidth() - x_pos < part_width){
               return newBufferedImage.getWidth() - x_pos;
           }
           else{
               return part_width;
           }
       }
   }
   
   public static void widthCutter(int y_pos) throws IOException{ //вырезает одну строчку и делит её на части
       int imgWidth = 0;
            while(!(imgWidth >= newBufferedImage.getWidth()))
            {                               
                if (widthRest(imgWidth) == 0 || heightRest(y_pos) ==0 || (widthRest(imgWidth) == 0 && heightRest(y_pos) == 0)){
                imgWidth = imgWidth + part_width;
                break;
                }                                
                partOfImage = new BufferedImage(widthRest(imgWidth), heightRest(y_pos), BufferedImage.TYPE_INT_RGB);
               
                partOfImage = newBufferedImage.getSubimage(imgWidth, y_pos, widthRest(imgWidth), heightRest(y_pos));
                                
                part_counter = part_counter + 1;
                
                saveImgPart();
                imgWidth = imgWidth + part_width;                
            }
   }
   
   public static void saveImgPart() throws IOException{ //сохраняет картинку
       ImageIO.write(partOfImage, "jpg", new File(output_dir + "\\part" + part_counter + ".jpg"));
   }

}