import os
import csv
import sys

class ForceUpdateVersion():
    def __init__(self):
        startVersion, endVersion, unset = self._get_sys_args()
        self.startVersion = startVersion
        self.endVersion = endVersion
        self.unset = unset
        self.hotfixPaths = ["Hotfix/Android/LV2.", "Hotfix/AndroidLow/LV2.", "Hotfix/iOS/LV2.", "Hotfix/iOSLow/LV2."]
        self.versionFile = "Version.csv"


    @staticmethod
    def _get_sys_args():
        # 读取命令行
        startVersion = 26
        if len(sys.argv) > 1:
            startVersion = int(sys.argv[1])

        endVersion = 27
        if len(sys.argv) == 3 and int(sys.argv[2]) == 1:
            endVersion = startVersion
            unset = True
        else:
            if len(sys.argv) > 2:
                endVersion = int(sys.argv[2])
            else:
                endVersion = startVersion

            unset = False
            if len(sys.argv) > 3:
                unset = sys.argv[3] == "1"

        return startVersion, endVersion, unset

    def iterate_and_set_force_update(self):
        # 遍历hotfixPaths
        for hotfixPath in self.hotfixPaths:
            for i in range(self.startVersion, self.endVersion + 1):
                hotfixPathVersion = hotfixPath + str(i) + "/" + self.versionFile
                if os.path.exists(hotfixPathVersion):
                    # 读取csv文件，把第4行开始的所有的ForceUpdate列设置为1
                    with open(hotfixPathVersion, "r") as fr:
                        reader = csv.reader(fr)
                        rows = [row for row in reader]
                        for row in rows[3:]:
                            # 目前第4列是ForceUpdate
                            if self.unset:
                                row[3] = "0"
                            else:
                                row[3] = "1"

                        # 写入文件，但是不要多余的空行
                        with open(hotfixPathVersion, "w", newline='') as fw:
                            writer = csv.writer(fw, lineterminator='\n')
                            writer.writerows(rows)

    def generate(self):
        self.iterate_and_set_force_update()

if __name__ == '__main__':
    ForceUpdateVersion().generate()
