Files
2025-04-11 15:49:22 +02:00

618 lines
18 KiB
Dart

import 'dart:convert';
import 'package:multimedia/widgets/tvshows/details/details_screen.dart';
import 'package:multimedia/widgets/tvshows/filter_box.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:intl/intl.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:syncfusion_flutter_core/theme.dart';
import 'package:multimedia/data/tvshows.dart';
import 'package:multimedia/constants.dart';
import 'package:logger/logger.dart';
import 'package:multimedia/log_printer.dart';
String convertState(String state) {
List<String> stateList = state.split(',');
int maxEpisode = 0;
Map stateListMap = {};
for (var x = 0; x < stateList.length; x++) {
List<String> tmp = stateList[x].split('|');
stateListMap[tmp[0]] = tmp[1];
int episode = int.parse(tmp[0]);
if (episode > maxEpisode) {
maxEpisode = episode;
}
}
String stateString = "";
for (int x = 0; x < maxEpisode; x++) {
String s = '0';
int key = x + 1;
if (stateListMap.containsKey('$key')) {
s = stateListMap['$key'];
}
stateString = stateString + s;
}
return stateString;
}
List<DataGridCell> setSeasonData(int maxSeason, List<Season> seasonList) {
List<DataGridCell> dataGridCell = [];
int length = seasonList.length;
for (int x = 1; x <= maxSeason; x++) {
String status = '';
if (x <= length) {
status = convertState(seasonList[x - 1].state);
}
dataGridCell.add(DataGridCell(columnName: 'season$x', value: status));
}
return dataGridCell;
}
class TVShowsScreen extends StatefulWidget {
const TVShowsScreen({
super.key,
});
@override
State<StatefulWidget> createState() => _TVShowsScreenState();
}
class _TVShowsScreenState extends State<TVShowsScreen> {
final DataGridController _dataGridController = DataGridController();
late int maxSeason;
late List<EpisodeCount> episodeCount;
late TVShowDataSource tvshowDataSource;
List<GridColumn> _columns = [];
late bool initDone = false;
late List<TVShow> _tvshowsList;
String searchText = '';
bool showInit = false;
bool showProg = false;
bool showDone = false;
Logger logger = getLogger();
Future<List<TVShow>> generateTVShowList() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String? dbProtocol = prefs.getString('dbProtocol');
String? dbHost = prefs.getString('dbHost');
String? dbPath = prefs.getString('dbPath');
Uri url = Uri(
scheme: dbProtocol,
host: dbHost,
path: dbPath,
queryParameters: {
'module': 'tvshow',
'function': 'getList',
},
);
try {
final response = await http.get(url);
//LATER bool? error;
//LATER String? errorMessage;
String? mSeason;
Map<String, dynamic> tvshows = json.decode(response.body);
//LATER error = tvshows['error'];
//LATER errorMessage = tvshows['errmsg'];
mSeason = tvshows['maxSeason'];
var tvshowList = tvshows['tvshows'];
var episodeList = tvshows['episodeCount'];
if (mSeason != null) {
if (int.tryParse(mSeason) != null) {
maxSeason = int.parse(mSeason);
}
}
List<TVShow> tvshowsTmp = await tvshowList
.map<TVShow>((json) => TVShow.fromJson(json))
.toList();
tvshowDataSource = TVShowDataSource(tvshowsTmp, maxSeason);
List<EpisodeCount> episodecountTmp = await episodeList
.map<EpisodeCount>((json) => EpisodeCount.fromJson(json))
.toList();
episodeCount = episodecountTmp;
if (initDone == false) {
addSeasonColumns(maxSeason);
}
initDone = true;
_tvshowsList = tvshowsTmp;
return tvshowsTmp;
} catch (e) {
print(e.toString());
}
return [];
}
void addSeasonColumns(int maxSeason) {
for (int x = 1; x <= maxSeason; x++) {
_columns.add(GridColumn(
columnName: 'season$x',
// columnWidthMode: ColumnWidthMode.auto,
label: Container(
padding: const EdgeInsets.all(4.0),
alignment: Alignment.centerLeft,
child: Text('Season $x'))));
}
}
List<GridColumn> getColumns() {
return <GridColumn>[
GridColumn(
columnName: 'seriesID',
visible: false,
width: 70,
label: Container(
padding: const EdgeInsets.all(4.0),
alignment: Alignment.centerLeft,
child: const Text('seriesID'),
),
),
GridColumn(
columnName: 'seriesState',
visible: false,
width: 70,
label: Container(
padding: const EdgeInsets.all(4.0),
alignment: Alignment.centerLeft,
child: const Text('seriesState'))),
GridColumn(
columnName: 'status',
visible: false,
width: 70,
label: Container(
padding: const EdgeInsets.all(4.0),
alignment: Alignment.centerLeft,
child: const Text('status'))),
GridColumn(
columnName: 'cliffhanger',
visible: false,
width: 70,
label: Container(
padding: const EdgeInsets.all(4.0),
alignment: Alignment.centerLeft,
child: const Text('cliffhanger'))),
GridColumn(
columnName: 'backdropPath',
visible: false,
width: 70,
label: Container(
padding: const EdgeInsets.all(4.0),
alignment: Alignment.centerLeft,
child: const Text('backdropPath'))),
GridColumn(
columnName: 'overview',
visible: false,
width: 70,
label: Container(
padding: const EdgeInsets.all(4.0),
alignment: Alignment.centerLeft,
child: const Text('overview'))),
GridColumn(
columnName: 'seriesName',
// columnWidthMode: ColumnWidthMode.auto,
label: Container(
padding: const EdgeInsets.all(4.0),
alignment: Alignment.centerLeft,
child: const Text('Name'))),
GridColumn(
columnName: 'firstAired',
// columnWidthMode: ColumnWidthMode.auto,
label: Container(
padding: const EdgeInsets.all(4.0),
alignment: Alignment.centerLeft,
child: const Text('First Aired'))),
GridColumn(
columnName: 'resolution',
// columnWidthMode: ColumnWidthMode.auto,
label: Container(
padding: const EdgeInsets.all(4.0),
alignment: Alignment.centerLeft,
child: const Text('Resolution'))),
];
}
@override
void initState() {
super.initState();
_columns = getColumns();
}
Future<void> showTVShowDetails(int index) async {
DataGridRow row = tvshowDataSource.effectiveRows.elementAt(index);
List<DataGridCell<dynamic>> cells = row.getCells();
String seriesID = cells[TVShowColumn.seriesID].value.toString();
bool found = false;
int tvShowIndex;
int realIndex;
tvshowDataSource.clearFilters();
realIndex = tvshowDataSource.rows.indexOf(row);
for (tvShowIndex = 0; tvShowIndex < _tvshowsList.length; tvShowIndex++) {
if (_tvshowsList[tvShowIndex].seriesID == int.parse(seriesID)) {
found = true;
break;
}
}
if (found) {
final t = await Navigator.push(
context,
MaterialPageRoute(
builder: (ctx) =>
TVShowDetailsScreen(tvShow: _tvshowsList[tvShowIndex])));
if (t != null) {
_tvshowsList[tvShowIndex].seriesName = t.seriesName;
_tvshowsList[tvShowIndex].download = t.download;
_tvshowsList[tvShowIndex].localPath = t.localPath;
_tvshowsList[tvShowIndex].resolution = t.resolution;
_tvshowsList[tvShowIndex].cliffhanger = t.cliffhanger;
_tvshowsList[tvShowIndex].seasonStatus = t.seasonStatus;
_tvshowsList[tvShowIndex].seriesState = t.seriesState;
TVShow e = _tvshowsList[tvShowIndex];
tvshowDataSource._tvshowDataGridRows[realIndex] = DataGridRow(cells: [
DataGridCell<int>(columnName: 'seriesID', value: e.seriesID),
DataGridCell<int>(columnName: 'seriesState', value: e.seriesState),
DataGridCell<String>(columnName: 'status', value: e.status),
DataGridCell<int>(columnName: 'cliffhanger', value: e.cliffhanger),
DataGridCell<String>(
columnName: 'backdropPath', value: e.backdropPath),
DataGridCell<String>(columnName: 'overview', value: e.overview),
DataGridCell<String>(columnName: 'seriesName', value: e.seriesName),
DataGridCell<String>(
columnName: 'firstAired',
value: DateFormat('yyyy-MM-dd').format(e.firstAired)),
DataGridCell<String>(columnName: 'resolution', value: e.resolution),
...setSeasonData(maxSeason, e.seasonStatus),
]);
for (int i = 0; i < _columns.length; i++) {
tvshowDataSource.updateDataGridSource(
rowColumnIndex: RowColumnIndex(realIndex, i));
}
} else {}
filter();
}
}
void setFilter(String text, bool sInit, bool sProg, bool sDone) {
searchText = text;
showInit = sInit;
showProg = sProg;
showDone = sDone;
filter();
}
void filter() {
tvshowDataSource.clearFilters();
if (showInit)
tvshowDataSource.addFilter(
'seriesState',
FilterCondition(
type: FilterType.equals,
value: 1,
filterOperator: FilterOperator.or),
);
if (showProg)
tvshowDataSource.addFilter(
'seriesState',
FilterCondition(
type: FilterType.equals,
value: 2,
filterOperator: FilterOperator.or,
));
if (showDone)
tvshowDataSource.addFilter(
'seriesState',
FilterCondition(
type: FilterType.equals,
value: 3,
filterOperator: FilterOperator.or,
));
tvshowDataSource.addFilter(
'seriesName',
FilterCondition(
type: FilterType.beginsWith,
value: searchText,
filterOperator: FilterOperator.and,
filterBehavior: FilterBehavior.stringDataType,
));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('TV Shows'),
actions: [
const VerticalDivider(
width: 10,
thickness: 3,
indent: 0,
endIndent: 0,
color: Colors.grey,
),
IconButton(
icon: const Icon(Icons.add_circle_outline),
tooltip: 'Add TV Show',
onPressed: () {
addTVShow();
// if (save()) {
// Navigator.pop(context, movieDetails);
// }
},
),
IconButton(
icon: const Icon(Icons.update_outlined),
tooltip: 'Update TVShows',
onPressed: () {
updateTVShows();
//todo
},
),
],
),
body: Column(
children: [
TVShowFilterBox(setFilter: setFilter),
Expanded(
child: FutureBuilder<Object>(
future: generateTVShowList(),
builder: (context, data) {
return data.hasData
? SfDataGridTheme(
data: const SfDataGridThemeData(
headerColor: Color(0xff009889),
),
child: SfDataGrid(
source: tvshowDataSource,
selectionMode: SelectionMode.single,
navigationMode: GridNavigationMode.row,
columns: _columns,
controller: _dataGridController,
columnWidthMode: ColumnWidthMode.auto,
columnWidthCalculationRange:
ColumnWidthCalculationRange.allRows,
onCellTap: (DataGridCellTapDetails details) {
int index = details.rowColumnIndex.rowIndex - 1;
if (index < 0) {
return;
}
showTVShowDetails(index);
},
onCellDoubleTap:
(DataGridCellDoubleTapDetails details) {
print(details.rowColumnIndex);
},
onCellLongPress:
(DataGridCellLongPressDetails details) {
print(details.rowColumnIndex);
},
onCellSecondaryTap: (DataGridCellTapDetails details) {
print(details.rowColumnIndex);
},
),
)
: const Center(
child: CircularProgressIndicator(
strokeWidth: 2,
value: 0.8,
),
);
},
),
),
],
),
);
}
void addTVShow() {
logger.i('add TV Show');
}
void searchTVShow() {
logger.i('search TV Show');
}
void updateTVShows() {
logger.i('update TV Shows');
}
}
class TVShowDataSource extends DataGridSource {
/// Creates the employee data source class with required details.
TVShowDataSource(this.tvshows, this.maxSeason) {
buildDataGridRow();
}
Logger logger = getLogger();
void buildDataGridRow() {
_tvshowDataGridRows = tvshows
.map<DataGridRow>((e) => DataGridRow(cells: [
DataGridCell<int>(columnName: 'seriesID', value: e.seriesID),
DataGridCell<int>(
columnName: 'seriesState', value: e.seriesState),
DataGridCell<String>(columnName: 'status', value: e.status),
DataGridCell<int>(
columnName: 'cliffhanger', value: e.cliffhanger),
DataGridCell<String>(
columnName: 'backdropPath', value: e.backdropPath),
DataGridCell<String>(columnName: 'overview', value: e.overview),
DataGridCell<String>(
columnName: 'seriesName', value: e.seriesName),
DataGridCell<String>(
columnName: 'firstAired',
value: DateFormat('yyyy-MM-dd').format(e.firstAired)),
DataGridCell<String>(
columnName: 'resolution', value: e.resolution),
...setSeasonData(maxSeason, e.seasonStatus),
]))
.toList();
}
List<TVShow> tvshows = [];
int maxSeason;
List<DataGridRow> _tvshowDataGridRows = [];
@override
List<DataGridRow> get rows => _tvshowDataGridRows;
Row generateSeasonState(String state) {
if (state.isEmpty) {
return const Row(
children: [Text('')],
);
}
List<Color> stateColor = [];
for (int x = 0; x < state.length; x++) {
Color c = StateColor.none;
if (state[x] == '1') {
c = StateColor.init;
} else if (state[x] == '2') {
c = StateColor.prog;
} else if (state[x] == '3') {
c = StateColor.done;
}
stateColor.add(c);
}
return Row(children: <Widget>[
...stateColor.map((col) => Text(
'1',
style: TextStyle(
fontFamily: 'geometric',
fontSize: 25,
color: col,
),
)),
]);
}
@override
DataGridRowAdapter buildRow(DataGridRow row) {
return DataGridRowAdapter(
cells: row.getCells().map<Widget>((e) {
Color colorBG = Colors.white;
Color colorFG = Colors.black;
FontWeight fontWeight = FontWeight.normal;
FontStyle fontStyle = FontStyle.normal;
if (e.columnName == 'seriesName') {
int seriesState =
row.getCells().toList()[TVShowColumn.seriesState].value;
String status = row.getCells().toList()[TVShowColumn.state].value;
int cliffhanger =
row.getCells().toList()[TVShowColumn.cliffhanger].value;
if (seriesState == 1) {
colorBG = StateColor.init;
} else if (seriesState == 2) {
colorBG = StateColor.prog;
colorFG = Colors.white;
} else {
colorBG = StateColor.done;
}
if (cliffhanger == 1) {
fontStyle = FontStyle.italic;
}
if (status == 'In Production' || status == 'Returning Series') {
fontWeight = FontWeight.bold;
}
}
if (e.columnName.startsWith('season')) {
Row row = generateSeasonState(e.value.toString());
return Container(
alignment: Alignment.center,
padding: const EdgeInsets.symmetric(horizontal: 16),
child: row,
);
}
if (e.columnName.startsWith('seriesName')) {
return Container(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.all(8.0),
color: colorBG,
child: Text(
e.value.toString(),
style: TextStyle(
color: colorFG,
fontWeight: fontWeight,
fontStyle: fontStyle,
),
),
);
}
return Container(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.all(8.0),
child: Text(
e.value.toString(),
style: TextStyle(
fontWeight: fontWeight,
fontStyle: fontStyle,
),
),
);
}).toList());
}
void updateDataGrid() {
notifyListeners();
}
void updateDataGridSource({required RowColumnIndex rowColumnIndex}) {
notifyDataSourceListeners(rowColumnIndex: rowColumnIndex);
}
}