package me.devsaki.hentoid.json.sources;

import androidx.annotation.NonNull;

import com.annimon.stream.Stream;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import me.devsaki.hentoid.util.Helper;

public class HitomiGalleryInfo {

    private List<HitomiGalleryPage> files;

    public List<HitomiGalleryPage> getFiles() {
        if (null == files) return Collections.emptyList();
            // Sort files by anything that resembles a number inside their names (Hitomi may order the pages wrongly)
        else return Stream.of(files).sorted(new InnerNameNumberComparator()).toList();
    }

    public static class HitomiGalleryPage {
        private String hash;
        private Integer haswebp;
        private String name;

        public String getHash() {
            return hash;
        }

        public Integer getHaswebp() {
            return haswebp;
        }

        public String getName() {
            return name;
        }
    }

    private static class InnerNameNumberComparator implements Comparator<HitomiGalleryPage> {
        @Override
        public int compare(@NonNull HitomiGalleryPage o1, @NonNull HitomiGalleryPage o2) {
            String name1 = o1.getName();
            if (null == name1) name1 = "";
            String name2 = o2.getName();
            if (null == name2) name2 = "";
            long innerNumber1 = Helper.extractNumeric(name1);
            if (-1 == innerNumber1) return name1.compareTo(name2);
            long innerNumber2 = Helper.extractNumeric(name2);
            if (-1 == innerNumber2) return name1.compareTo(name2);

            return Long.compare(innerNumber1, innerNumber2);
        }
    }
}
@@ -190,16 +190,59 @@
 .List;%0A%0A
+import me.devsaki.hentoid.util.FileHelper;%0A
 import m
@@ -1001,24 +1001,46 @@
       return
+ (null == name) ? %22%22 :
  name;%0A     
@@ -1311,251 +1311,284 @@
     
-if (null == name1) name1 = %22%22;%0A            String name2 = o2.getName();%0A            if (null == name2) name2 = %22%22;%0A            long inner
+String name2 = o2.getName();%0A            // Compare only when the entire file name is numerical (see follow-up comments on #640)%0A            if (Helper.is
 Num
-b
 er
-1 = Helper.extractNumeric(name1);%0A            if (-1 == inner
+ic(FileHelper.getFileNameWithoutExtension(name1)) && Helper.is
 Num
-b
 er
-1) return name1.compareTo
+ic(FileHelper.getFileNameWithoutExtension
 (name2)
-;
+))
 %0A   
@@ -1600,27 +1600,61 @@
     
-long inner
+    return Long.compare(Helper.extract
 Num
-b
 er
-2 =
+ic(name1),
  Hel
@@ -1678,16 +1678,17 @@
 c(name2)
+)
 ;%0A      
@@ -1697,64 +1697,17 @@
     
-if (-1 == innerNumber2) return name1.compareTo(name2);%0A%0A
+else%0A    
     
@@ -1721,28 +1721,29 @@
  return 
-Long
+name1
 .compare
 (innerNu
@@ -1738,34 +1738,15 @@
 pare
-(innerNumber1, innerNumber
+To(name
 2);%0A

Fix #640 hopefully for good