//     Sofaraum client is the client software which collects statistics about
//     wifi devices nearby and then sends them to the Sofaraum Server.
//     Copyright (c) 2018.
//
//     This program is free software: you can redistribute it and/or modify
//     it under the terms of the GNU General Public License as published by
//     the Free Software Foundation, either version 3 of the License, or
//     (at your option) any later version.
//
//     This program is distributed in the hope that it will be useful,
//     but WITHOUT ANY WARRANTY; without even the implied warranty of
//     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//     GNU General Public License for more details.
//
//     You should have received a copy of the GNU General Public License
//     along with this program.  If not, see <https://www.gnu.org/licenses/>.

package processing

import (
	"bufio"
	"bytes"
	"encoding/csv"
	"git.kolaente.de/sofaraum/client/pkg/config"
	"git.kolaente.de/sofaraum/client/pkg/models"
	"git.kolaente.de/sofaraum/client/pkg/utils"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

// ParseCSVDumps extracts data from airdump-ng's csv files in a format we can handle
func ParseCSVDumps(pathToDumps string) (clients []*models.WifiClient) {
	err := filepath.Walk(pathToDumps, func(dumpPath string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		// Only csv files
		if info.IsDir() || filepath.Ext(dumpPath) != ".csv" {
			return nil
		}

		bs, err := ioutil.ReadFile(dumpPath)
		if err != nil {
			log.Fatal(err)
		}
		all := string(bs)
		i := 0
		i = strings.Index(all, config.TheClientCSVHeader)
		arefun := all[i+len(config.TheClientCSVHeader)+1:]
		arefun = strings.Replace(arefun, " ", "", -1)

		scanner := bufio.NewScanner(strings.NewReader(arefun))
		for scanner.Scan() {
			r := csv.NewReader(bytes.NewReader(scanner.Bytes()))
			record, err := r.Read()
			if err != nil {
				if err.Error() == "EOF" {
					continue
				}
				log.Fatal(err)
			}

			power, err := strconv.ParseInt(record[3], 10, 64)
			if err != nil {
				log.Fatal(err)
			}

			packets, err := strconv.ParseInt(record[4], 10, 64)
			if err != nil {
				log.Fatal(err)
			}

			clients = append(clients, &models.WifiClient{
				MACAdress: record[0],
				FirstSeen: utils.ParseDateToUnix(record[1]),
				LastSeen:  utils.ParseDateToUnix(record[2]),
				Power:     power,
				Packets:   packets,
			})
		}

		return nil
	})

	if err != nil {
		log.Fatal(err)
	}

	return
}
